package com.dfish.downloadtool;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import android.app.Service;
import android.content.Intent;
import android.content.SharedPreferences;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Binder;
import android.os.IBinder;

public class MyService extends Service {
    private MyBinder myBinder = new MyBinder();
    public boolean IsStopDownload = true;
    List<RtspThread> threadLists;
    private int port = 2000;
    private Timer mTimer;
    private TimerTask mTimerTask;

    @Override
    public IBinder onBind(Intent intent) {
        DDebug.logd("onBind");
        return myBinder;
    }

    @Override
    public void onRebind(Intent intent) {
        DDebug.logd("onRebind");
        super.onRebind(intent);
    }

    @Override
    public boolean onUnbind(Intent intent) {
        DDebug.logd("onUnbind");
        return super.onUnbind(intent);
    }
    
    private boolean readBooleanPreferences(String perferencesName, String key) {
        SharedPreferences preferences = getSharedPreferences(perferencesName, MODE_PRIVATE);
        boolean result = preferences.getBoolean(key, false);
        return result;
    }
    
    @Override
    public void onCreate() {
        DDebug.logd("onCreate");
        super.onCreate();
        threadLists = new ArrayList<RtspThread>();
        startRecordData();
    }
    
    public void startRecordData() {
        if (mTimerTask == null) {
            mTimerTask = new TimerTask() {
                @Override
                public void run() {
                    if (MainActivity.mDownloadData > 0) {
                        writePreferences(MainActivity.RTSP_NAME,
                                MainActivity.RTSP_TOTAL, MainActivity.mDownloadData);
                        DDebug.logd("value:" + MainActivity.mDownloadData);
                    }

                    if (MainActivity.mMaxData > 0
                            && MainActivity.mDownloadData >= MainActivity.mMaxData) {
                        MainActivity.isRunning = false;
                        closeRtsp();
                        gameOver();
                    }
                }
            };
        }
        
        if (mTimerTask != null) {
            if (mTimer == null) {
                mTimer = new Timer();
            }
            
            try {
                mTimer.schedule(mTimerTask, 2000, 3000);
            } catch (IllegalStateException e) {
                if (mTimer != null) {
                    mTimer.cancel();
                    mTimer = null;
                }

                if (mTimerTask != null) {
                    mTimerTask.cancel();
                    mTimerTask = null;
                }
                
                startRecordData();
            }
        }
    }
    
    public void gameOver() {
        if (threadLists != null) {
            for (RtspThread r : threadLists) {
                if(r != null && !r.isInterrupted()) {
                    r.interrupt();
                }
            }
            threadLists.clear();
        }
        
        if(!readBooleanPreferences(MainActivity.RTSP_NAME, 
                MainActivity.STOP_MUSIC)) {
            notifyOver();
        }
    }

    private void writePreferences(String perferencesName, String key, long value) {
        SharedPreferences preferences = getSharedPreferences(perferencesName, 0);
        SharedPreferences.Editor editor = preferences.edit();
        editor.putLong(key, value).commit();
    }
    
    @Override
    public void onDestroy() {
        DDebug.logd("onDestroy");
        super.onDestroy();
        
        if (mTimer != null) {  
            mTimer.cancel();  
            mTimer = null;  
        }  
  
        if (mTimerTask != null) {  
            mTimerTask.cancel();  
            mTimerTask = null;  
        } 
    }

    @Override
    public void onStart(Intent intent, int startId) {
        DDebug.logd("onStart");
        super.onStart(intent, startId);
    }

    private class RtspThread extends Thread {
        ReadRstpData readRstpData;
        RtspThread(String url, int port) {
            readRstpData = new ReadRstpData(MyService.this, url, port);
        }
        
        public void run() {
            readRstpData.setupRtsp();
        }
        
        public void downloadData(String url) {
            readRstpData.restartDownload(url);
        }
        
        public void closeRtsp() {
            try {
                readRstpData.closeRtsp();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
    
    public void setupRtsp(final String url, int number) {
        if (threadLists != null) {
            if (threadLists.size() == 0) {
                for (int i = 0; i < number; i++) {
                    RtspThread thread = new RtspThread(url, port + i);
                    thread.start();
                    threadLists.add(thread);
                }
            } else {
                for (RtspThread r : threadLists) {
                    r.downloadData(url);
                }
            }
        }
    }
    
    public void closeRtsp() {
        if (threadLists != null) {
            for (RtspThread r : threadLists) {
                r.closeRtsp();
            }
        }
    }

    public class MyBinder extends Binder {
        MyService getService() {
            return MyService.this;
        }
    }
    
    private MediaPlayer mMediaPlayer;
    
    private void notifyOver() {
        if(mMediaPlayer != null && mMediaPlayer.isPlaying())
            return;
         mMediaPlayer = MediaPlayer.create(this, R.raw.yudao);
         mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
         mMediaPlayer.setLooping(true);
         mMediaPlayer.start();
    }
    
    public void stopPlaying(){
         if(mMediaPlayer != null && mMediaPlayer.isPlaying()){
             mMediaPlayer.stop();
         }   
         mMediaPlayer = null;
    }
}
